const { Sequelize } = require('sequelize');

// 数据库配置
const config = require('./config/config.default.js')({ name: 'lingxi-system' });

// 创建 Sequelize 实例
const sequelize = new Sequelize(config.sequelize.database, config.sequelize.username, config.sequelize.password, {
  host: config.sequelize.host,
  dialect: config.sequelize.dialect,
  port: config.sequelize.port,
  timezone: config.sequelize.timezone,
  logging: false
});

async function checkLatestSalesData() {
  try {
    // 测试数据库连接
    await sequelize.authenticate();
    console.log('✅ 数据库连接成功');
    
    // 查询最新的10条销售订单记录
    console.log('\n🔍 查询最新的销售订单...');
    const [orders] = await sequelize.query(`
      SELECT 
        id,
        order_no,
        platform_order_id,
        customer_id,
        order_amount,
        order_status,
        order_date,
        platform_source,
        invoice_status,
        invoice_date,
        responsible_salesman,
        is_gift,
        created_at,
        updated_at
      FROM sales_orders 
      ORDER BY created_at DESC 
      LIMIT 10
    `);
    
    console.log(`📋 找到 ${orders.length} 条销售订单记录:`);
    orders.forEach((order, index) => {
      console.log(`\n订单 ${index + 1}:`);
      console.log(`  ID: ${order.id}`);
      console.log(`  订单编号: ${order.order_no}`);
      console.log(`  平台订单ID: ${order.platform_order_id}`);
      console.log(`  客户ID: ${order.customer_id}`);
      console.log(`  订单金额: ${order.order_amount}`);
      console.log(`  订单状态: ${order.order_status}`);
      console.log(`  订单日期: ${order.order_date}`);
      console.log(`  平台来源: ${order.platform_source}`);
      console.log(`  开票状态: ${order.invoice_status}`);
      console.log(`  负责销售: ${order.responsible_salesman || '未指定'}`);
      console.log(`  是否赠品: ${order.is_gift ? '是' : '否'}`);
      console.log(`  创建时间: ${order.created_at}`);
    });
    
    // 统计订单总数
    const [countResult] = await sequelize.query('SELECT COUNT(*) as count FROM sales_orders');
    console.log(`\n📊 销售订单总数量: ${countResult[0].count}`);
    
    // 检查是否有来自政采云的数据
    const [zcyCountResult] = await sequelize.query("SELECT COUNT(*) as count FROM sales_orders WHERE platform_source = 'zcy'");
    console.log(`\n🏢 政采云订单数量: ${zcyCountResult[0].count}`);
    
  } catch (error) {
    console.error('❌ 查询销售订单时出错:', error.message);
  } finally {
    await sequelize.close();
  }
}

checkLatestSalesData();